import {
  getCatlist,
  getPersonalized,
  getNewestList,
  reqTrackAll,
  reqDetailList,
} from "@/api";
const state = {
  songList: {},
  recommendsongList: [],
  newAlbum: [],
  newTrackList: JSON.parse(localStorage.getItem("playlist")) || [],
};
const mutations = {
  GETSONGLIST(state, data) {
    state.songList = data || {};
  },
  GETRECOMMENDSONGLIST(state, data) {
    state.recommendsongList = data || [];
  },
  GETNEWALBUM(state, data) {
    state.newAlbum = data || [];
  },
  ADDTRACKALL(state, data) {
    state.newTrackList = data || [];
  },
};

const actions = {
  // 获取歌单分类
  async getSongList({ commit }) {
    const resule = await getCatlist();
    // console.log(rustle)
    if (resule.code == 200) {
      commit("GETSONGLIST", resule);
    }
  },
  // 获取随机推荐歌单  getPersonalized
  async getRecommendSongList({ commit }) {
    const results = await getPersonalized();
    // console.log(results.result)
    if (results.code == 200) {
      commit("GETRECOMMENDSONGLIST", results.result);
    }
  },
  // 获取最新专辑
  async getNewAlbum({ commit }) {
    const result = await getNewestList();
    // console.log(result)
    if (result.code == 200) {
      commit("GETNEWALBUM", result.albums);
    }
  },
  // 添加到歌单列表
  async addTrackAll({ commit }, params) {
    // addTrackAll
    const result = await reqTrackAll(params);
    //  console.log(result)
    if (result.code == 200) {
      // this.newTrackList = result.songs || [];
      commit("ADDTRACKALL", result.songs);
      localStorage.removeItem("playlist");
      localStorage.setItem("playlist", JSON.stringify(result.songs));
    } else {
      alert("添加榜单失败");
    }
  },
  // 获取歌曲详情
  async getDetailList({ commit }, ids) {
    // 获取传过来的id
    const result = await reqDetailList(ids);
    console.log(result);
    // 读取
    const newplaylist = JSON.parse(localStorage.getItem("playlist"));
    if (result.code == 200) {
      if (newplaylist == null) {
        // 如果等于null就自己创一个
        localStorage.setItem("playlist", JSON.stringify(result.songs));
        // 传给上面渲染
        commit('ADDTRACKALL',result.songs)
      } else {
        // 添加一个
        newplaylist.push(result.songs[0]);
        // 重写到本地
        localStorage.setItem("playlist", JSON.stringify(newplaylist));
        // 重写读取给上面渲染达到双向目的
        let news = JSON.parse(localStorage.getItem("playlist"));
        // 传给上面
        commit('ADDTRACKALL',news)
      }
    } else {
      alert("添加失败");
    }
  },
};

const getters = {};

export default {
  state,
  mutations,
  actions,
  getters,
};
